//
//  FZComponsePictureView.swift
//  FZSina_Swift
//
//  Created by 李忠 on 7/26/16.
//  Copyright © 2016 FZLZ. All rights reserved.
//

import UIKit
private let pictureId = "composePictureId"
class FZComponsePictureView: UICollectionView {
    
    
    //保存图片的数组
    private var listImage: [UIImage] = [UIImage]()
    var addImageCloure: (()->())?
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
        
        dataSource = self
        delegate = self
    }
    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        
        self.backgroundColor = RANDRGB()
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        let tempW: CGFloat = SCREENW - 2 * PADDING
        let cellMargin:CGFloat = 5.0
        let cellW = CGFloat(tempW - 2.0 * cellMargin) / 3.0
        
        flowLayout.itemSize = CGSizeMake(cellW, cellW)
        flowLayout.minimumLineSpacing = cellMargin
        flowLayout.minimumInteritemSpacing = cellMargin
        
        self.registerClass(FZComponsePictureCell.self, forCellWithReuseIdentifier: pictureId)
        
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handlelongGesture(_:)))
        
        self.addGestureRecognizer(longPress)
    }
    
    func handlelongGesture(long: UILongPressGestureRecognizer) {
        
        let indexPath = self.indexPathForItemAtPoint(long.locationInView(self))
        guard let ip = indexPath else{
            return
        }
        switch long.state {
        case .Possible:
            
            
            
            break
        case .Began:
            
            
            self.beginInteractiveMovementForItemAtIndexPath(ip)
            break
        case .Changed:

            self.updateInteractiveMovementTargetPosition(long.locationInView(self))
            break
        case .Ended:
            self.endInteractiveMovement()
            break
        default:
            self.cancelInteractiveMovement()
            break
        }
    }
    
    
//MARK:==========================向数组中添加图片==========================
    func addImageForList(image: UIImage) {
    
        listImage.append(image)
        
        //刷新数组
        reloadData()
    }
}

extension FZComponsePictureView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if self.listImage.count == 0 || self.listImage.count == 9 {
            return self.listImage.count
        }
        
        return self.listImage.count + 1
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureId, forIndexPath: indexPath) as! FZComponsePictureCell
        if self.listImage.count == indexPath.item {
            cell.image = nil
        }else{
            cell.image = listImage[indexPath.item]
        }
        cell.deleteCloure = {
            self.listImage.removeAtIndex(indexPath.item)
            self.reloadData()
        }
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: false)
        
        if listImage.count == indexPath.item {
            
            addImageCloure?()
            
        }
    }
    
    func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
        
        if destinationIndexPath.item == listImage.count {
            return
        }
        let  cel  = listImage[sourceIndexPath.item]
        listImage.removeAtIndex(sourceIndexPath.item)
        listImage.insert(cel, atIndex: destinationIndexPath.item)
        
        
    }
    func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        if listImage.count == indexPath.item {
            
            return false
            
        }

        return true
    }
    
}


class FZComponsePictureCell: UICollectionViewCell {
    
    var deleteCloure:(()->())?
    
    var  image: UIImage?{
        didSet{
            if image == nil {
                
                viewIMG.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                viewIMG.image = UIImage(named: "compose_pic_add")
                deleIMGButton.hidden = true
                
            }else{
                
                viewIMG.image = image
                viewIMG.highlightedImage = nil
                deleIMGButton.hidden = false
            }
        }
    }
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(viewIMG)
        contentView.addSubview(deleIMGButton)
        
        viewIMG.snp_makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        deleIMGButton.snp_makeConstraints { (make) in
            make.top.trailing.equalTo(contentView)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    lazy var viewIMG: UIImageView = UIImageView()
    lazy var deleIMGButton: UIButton = {
        let btn: UIButton = UIButton ()
        btn.addTarget(self, action: #selector(deleteIMGClick), forControlEvents: UIControlEvents.TouchUpInside)
        btn.setImage(UIImage(named:"compose_photo_close"), forState: UIControlState.Normal)
        
        return btn
    }()
    
    
    func deleteIMGClick() {
        deleteCloure?()
    }
    
}
